import json

from django.http import JsonResponse
from django.views import View
from app.models import *
from app.url import *


# 活动信息
class ActivityView(View):

    # 获取活动信息及报名用户头像信息
    def get(self, request):
        try:
            # 获取所有活动
            activitys = Activity.objects.all()
            data = []
            for activity in activitys:
                # 获取活动报名用户头像
                user_avatar = []
                user_url = Application.objects.select_related('user').select_related('user__userinfo').select_related(
                    'activity').filter(activity_id=activity.id)
                print(user_url)
                # 获取报名用户头像
                for u in user_url:
                    print(user_url.count())
                    user_avatar.append(u.user.userinfo.avatar)
                # 将信息添加到列表中
                data.append({
                    'name': activity.name,
                    'poster': get_server_url(request) + activity.poster,
                    'place': activity.place,
                    'end_time': activity.end_time,
                    'userUrl': user_avatar,
                    "id": activity.id,
                    'scale': activity.scale,
                    'company': activity.company,
                })
            return JsonResponse({
                'code': 200,
                'data': {
                    'result': data
                },
                'msg': '获取成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': '服务器内部错误'
            })

    # 删除活动
    def delete(self, request):
        # 获取活动id
        a_id = request.POST.get('a_id')
        Activity.objects.delete(id=a_id)
        return JsonResponse({
            'code': 200,
            'msg': '活动删除成功'
        })


# 活动详情
class ActivityDetailsView(View):
    # 获取活动详情
    def get(self, request):
        try:
            # 获取活动id
            a_id = request.GET.get('a_id')
            print(a_id)
            # 获取活动详情
            activity = Activity.objects.get(id=a_id)
            return JsonResponse({
                'code': 200,
                'data': {
                    'result': {
                        'id': activity.id,
                        'poster': get_server_url(request) + activity.poster,
                        'name': activity.name,
                        'place': activity.place,
                        'start_time': activity.start_time,
                        'end_time': activity.end_time,
                        'description': activity.description,
                        'Participating_units': activity.Participating_units,
                        'scale': activity.scale,
                        'company': activity.company
                    }
                },
                'msg': '获取成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })

    # 参与活动
    def post(self, request):

        try:
            params = json.loads(request.body)
            print(params)
            # 获取用户id
            userid = params['u_id']
            print(userid, '-================================')
            # 获取活动id
            activityid = params['a_id']
            # 创建报名记录
            Application.objects.create(id=uuid.uuid4(), user_id=userid, activity_id=activityid, commitment=True)

            # 获取活动名称
            activity_name = Activity.objects.get(id=activityid)
            return JsonResponse({
                'code': 200,
                'msg': '参与成功',
                'data': {
                    'result': {
                        'activity_name': activity_name.name,
                        'flag': True
                    }
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })

    # 取消活动同意书
    def put(self, request):
        try:
            # 获取用户id
            userid = request.GET.get('u_id', '')
            flag = not request.GET.get('flag', False)
            if not flag:
                Application.objects.filter(user__id=userid).update(commitment=False)
            else:
                Application.objects.filter(user__id=userid).update(commitment=True)
            return JsonResponse({
                'code': 200,
                'msg': '报名取消成功',
                'flag': False
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'报名取消失败：{str(e)}'
            })


# 我参加的活动
class MyJoinActivityView(View):
    # 获取我参加的活动
    def get(self, request):
        try:
            # 获取用户id
            u_id = request.GET.get('u_id')
            # 获取我参加的活动
            data = []
            my_join_activity = Application.objects.select_related('activity').select_related('user').filter(
                user__id=u_id)
            for m in my_join_activity:
                data.append({
                    'id': m.activity.id,
                    'name': m.activity.name,
                    'poster': get_server_url(request) + m.activity.poster,
                    'end_time': m.activity.end_time,
                    'status': m.activity.status,
                    'company': m.activity.company,
                    'scale': m.activity.scale
                })
            print(data)
            return JsonResponse({
                'code': 200,
                'msg': '获取成功',
                'data': {
                    'result': data
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器内部错误 ${e}'
            })


# 获取活动承诺书状态
class LetterOfCommitment(View):
    # 获取承诺书状态
    def get(self, request):
        try:
            # 获取用户id
            u_id = request.GET.get('u_id')
            print(u_id)
            # 获取承诺书状态
            letter_commitment = Application.objects.filter(user__id=u_id).first()
            return JsonResponse({
                'code': 200,
                'msg': '获取成功',
                'data': {
                    'result': letter_commitment.commitment
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器内部错误  err${e}'
            })


# 取消活动同意书
class CancelCommitment(View):
    # 取消活动同意书
    def post(self, request):
        try:
            # 获取用户id
            userid = request.POST.get('u_id', '')
            flag = request.POST.get('flag', '')
            print(userid)
            if flag == 'false':
                Application.objects.filter(user__id=userid).update(commitment=False)
            else:
                print('111')
                Application.objects.filter(user__id=userid).update(commitment=True)
            return JsonResponse({
                'code': 200,
                'msg': '报名取消成功',
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'报名取消失败：{str(e)}'
            })
